﻿using StartEAS_API.Utils;
using StartsEAS_API.DAL.DALTools;
using StartsEAS_API.Model;
using StartsEAS_API.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StartsEAS_API.DAL.ScheduleD
{
    public class ScheduleDAL
    {
        private readonly StarsEASContext _context;
        public ScheduleDAL(StarsEASContext context) { 
            _context = context;
        }
        public ResultUtils InsertSchedule(List<Schedule> scheduleList) {
            StarsEASContext _context = new StarsEASContext();
            if (scheduleList == null)
            {
                AppLog.WriteError($"添加课表信息---课表信息为空", true);
                return new ResultUtils() { code = 500, message = "课表信息为空" };
            }
            int num = 0;
            foreach (Schedule item in scheduleList) {
                item.ScheduleId = 0;
                Schedule pd1 = _context.Schedules.Where(s =>
                s.ScheduleWeekly == item.ScheduleWeekly &&
                s.ScheduleWeek == item.ScheduleWeek &&
                s.ScheduleWhat == item.ScheduleWhat &&
                s.Semester == item.Semester &&
                (s.ClassId == item.ClassId || s.WorkerId == item.WorkerId || s.SchedulePlace == item.SchedulePlace)
                ).FirstOrDefault();
                string EarrangeTime = item.SchoolSemester + "-" + item.ScheduleWeekly + "-" + item.ScheduleWeek + "-" + item.ScheduleWhat;
                Earrange pd2 = _context.Earranges.Where(e =>
                e.EarrangeTime == EarrangeTime &&
                (e.ClassId == item.ClassId || e.WorkerId == item.WorkerId || e.SchedulePlace == item.SchedulePlace)
                ).FirstOrDefault();
                if (pd1 != null || pd2 != null ) {
                    AppLog.WriteError($"添加课程---老师或班级或教室占用，添加失败,成功添加{num}条", true);
                    return new ResultUtils() { code = 500, message = $"老师或班级或教室占用，添加失败,成功添加{num}条" };
                }
                _context.Schedules.Add(item);
                num += _context.SaveChanges();
                AppLog.WriteInfo($"添加课表信息---上课时间：{item.ScheduleWeekly}-{item.ScheduleWeek}-{item.ScheduleWhat}\t上课教室：{item.SchedulePlace}\t上课老师：{item.WorkerId}\t课程编号：{item.CourseId}\t班级{item.ClassId}", true);
            }
            AppLog.WriteInfo($"添加课表信息---成功添加信息{num}条", true);
            return new ResultUtils() { code = 200, message = num };
        }

        public ResultUtils GetSchedultByClassId(string classId) {
            StarsEASContext _context = new StarsEASContext();
            var data = _context.Schedules.Where(s => s.ClassId == classId)
                .Join(_context.Courses,sc => sc.CourseId,cou => cou.CourseId,(sc,cou) => 
                    new {
                        ScheduleId = sc.ScheduleId,
                        SchoolSemester = sc.SchoolSemester,
                        CollegeId = sc.CollegeId,
                        ScheduleWeekly = sc.ScheduleWeekly,
                        ScheduleWeek = sc.ScheduleWeek,
                        ScheduleWhat = sc.ScheduleWhat,
                        WorkerId = sc.WorkerId,
                        SchedulePlace = sc.SchedulePlace,
                        Course = cou.CourseName,
                        ClassId = sc.ClassId,
                        Semester = sc.Semester
                    }
                );
            AppLog.WriteInfo($"课表查询---查询{classId}班课表信息", true);
            return new ResultUtils() { code = 200, message = data };
        }

        public ResultUtils GetSchedultByWorkerId(string token)
        {
            StarsEASContext _context = new StarsEASContext();
            User user = _context.Users.Where(u => u.Token.Equals(token)).FirstOrDefault();
            if (user == null)
            {
                AppLog.WriteError($"查询课表信息---账户{token}尝试登录但登录失败", true);
                return new ResultUtils() { code = 500, message = "Token无效" };
            }
            Worker worker = token.GetWorkerByToken(_context);
            var data = _context.Schedules.Where(s => s.WorkerId.Equals(worker.WorkerId))
                .Join(_context.Courses, sc => sc.CourseId, cou => cou.CourseId, (sc, cou) =>
                       new {
                           ScheduleId = sc.ScheduleId,
                           SchoolSemester = sc.SchoolSemester,
                           CollegeId = sc.CollegeId,
                           ScheduleWeekly = sc.ScheduleWeekly,
                           ScheduleWeek = sc.ScheduleWeek,
                           ScheduleWhat = sc.ScheduleWhat,
                           WorkerId = sc.WorkerId,
                           SchedulePlace = sc.SchedulePlace,
                           Course = cou.CourseName,
                           ClassId = sc.ClassId,
                           Semester = sc.Semester
                       }
                );
            AppLog.WriteInfo($"课表信息查询---老师{worker.WorkerName}查询课表", true);
            return new ResultUtils() { code = 200, message = data };
        }

        public ResultUtils GetSchedultBySchedulePlace(string SchedulePlace)
        {
            StarsEASContext _context = new StarsEASContext();
            var data = _context.Schedules.Where(s => s.SchedulePlace == SchedulePlace)
                .Join(_context.Courses, sc => sc.CourseId, cou => cou.CourseId, (sc, cou) =>
                       new {
                           ScheduleId = sc.ScheduleId,
                           SchoolSemester = sc.SchoolSemester,
                           CollegeId = sc.CollegeId,
                           ScheduleWeekly = sc.ScheduleWeekly,
                           ScheduleWeek = sc.ScheduleWeek,
                           ScheduleWhat = sc.ScheduleWhat,
                           WorkerId = sc.WorkerId,
                           SchedulePlace = sc.SchedulePlace,
                           Course = cou.CourseName,
                           ClassId = sc.ClassId,
                           Semester = sc.Semester
                       }
                );
            AppLog.WriteInfo($"课表信息查询---查询教室{SchedulePlace}课表", true);
            return new ResultUtils() { code = 200, message = data };
        }


        public ResultUtils GetSchedultByToken(string token)
        {
            StarsEASContext _context = new StarsEASContext();
            User user = _context.Users.Where(u => u.Token.Equals(token)).FirstOrDefault();
            if (user == null)
            {
                AppLog.WriteError($"查询课表信息---账户{token}尝试登录但登录失败", true);
                return new ResultUtils() { code = 500, message = "Token无效" };
            }
            if (token.IsStudent(_context))
            {
                Model.Models.Student student = token.GetStudentByToken(_context);
                var data = _context.Schedules.Where(s => s.ClassId == student.ClassId)
                    .Join(_context.Courses, sc => sc.CourseId, cou => cou.CourseId, (sc, cou) =>
                           new {
                               ScheduleId = sc.ScheduleId,
                               SchoolSemester = sc.SchoolSemester,
                            CollegeId = sc.CollegeId,
                            ScheduleWeekly = sc.ScheduleWeekly,
                            ScheduleWeek = sc.ScheduleWeek,
                            ScheduleWhat = sc.ScheduleWhat,
                            WorkerId = sc.WorkerId,
                            SchedulePlace = sc.SchedulePlace,
                            Course = cou.CourseName,
                            ClassId = sc.ClassId,
                            Semester = sc.Semester,
                           }
                    );
                AppLog.WriteInfo($"课表信息查询---学生{student.StuName}查询课表信息", true);
                return new ResultUtils() { code = 200, message = data };
            }
            else {
                Worker worker = token.GetWorkerByToken(_context);
                var data = _context.Schedules.Where(s => s.WorkerId.Equals(worker.WorkerId))
                    .Join(_context.Courses, sc => sc.CourseId, cou => cou.CourseId, (sc, cou) =>
                           new {
                               ScheduleId = sc.ScheduleId,
                               SchoolSemester = sc.SchoolSemester,
                               CollegeId = sc.CollegeId,
                               ScheduleWeekly = sc.ScheduleWeekly,
                               ScheduleWeek = sc.ScheduleWeek,
                               ScheduleWhat = sc.ScheduleWhat,
                               WorkerId = sc.WorkerId,
                               SchedulePlace = sc.SchedulePlace,
                               Course = cou.CourseName,
                               ClassId = sc.ClassId,
                               Semester = sc.Semester
                           }
                    );
                AppLog.WriteInfo($"查询课表信息---老师{worker.WorkerName}查询课表信息", true);
                return new ResultUtils() { code = 200, message = data };
            }
        }

        public int AdjustTheCourse(Schedule data) {
            StarsEASContext _context = new StarsEASContext();
            if (data == null) {
                AppLog.WriteError($"调节课程---课程信息未传入", true);
                return 0;
            }
            Schedule schedule = _context.Schedules.Find(data.ScheduleId);
            if (schedule == null) {
                AppLog.WriteError($"调节课程---未查询到对应的课程信息", true);
                return 0;
            }
            Schedule pd1 = _context.Schedules.Where(s => 
            s.ScheduleWeekly == data.ScheduleWeekly &&
            s.ScheduleWeek == data.ScheduleWeek &&
            s.ScheduleWhat == data.ScheduleWhat &&
            s.Semester == data.Semester &&
            (s.ClassId == data.ClassId || s.WorkerId==data.WorkerId || s.SchedulePlace==data.SchedulePlace)
            ).FirstOrDefault();
            string EarrangeTime = data.SchoolSemester + "-" + data.ScheduleWeekly + "-" + data.ScheduleWeek + "-" + data.ScheduleWhat;
            Earrange pd2 = _context.Earranges.Where(e =>
            e.EarrangeTime == EarrangeTime &&
            (e.ClassId == data.ClassId || e.WorkerId == data.WorkerId || e.SchedulePlace == data.SchedulePlace)
            ).FirstOrDefault();
            if (pd1 != null || pd2 !=null) {
                AppLog.WriteError($"调节课程---老师或班级或教室占用，调节失败", true);
                return 0;
            }
            schedule.SchedulePlace = data.SchedulePlace;
            schedule.ScheduleWhat = data.ScheduleWhat;
            schedule.ScheduleWeek = data.ScheduleWeek;
            schedule.ScheduleWeekly = data.ScheduleWeekly;
            schedule.ClassId = data.ClassId;
            schedule.CollegeId = data.CollegeId;
            schedule.SchoolSemester = data.SchoolSemester;
            schedule.Semester = data.Semester;
            int result = _context.SaveChanges();
            if (result == 0) {
                AppLog.WriteError($"调节课程---调节失败", true);
                return result;
            }
            AppLog.WriteInfo($"调节课程---调节成功", true);
            return result;
        }

        public ResultUtils GetWorkerEvaluationByStudent(string token,int Semester)
        {
            StarsEASContext _context = new StarsEASContext();
            User user = _context.Users.Where(u => u.Token.Equals(token)).FirstOrDefault();
            if (user == null)
            {
                AppLog.WriteError($"查询学生教评信息---账户{token}尝试登录但登录失败", true);
                return new ResultUtils() { code = 500, message = "Token无效" };
            }
            if (token.IsStudent(_context))
            {
                Model.Models.Student student = token.GetStudentByToken(_context);
                if (student == null) {
                    AppLog.WriteError($"查询学生教评信息---查询学生需要教评的课程错误，无{user.Username}学生", true);
                    return new ResultUtils() { code = 500, message = $"查询学生教评信息---查询学生需要教评的课程错误，无{user.Username}学生" };
                }
                //IEnumerable<Schedule> score = _context.Schedules.Where(s=>s.ClassId == student.ClassId && s.Semester == Semester).OrderByDescending(x=>x.CourseId).ToList();
                var scores = (from schedule in _context.Schedules
                             join course in _context.Courses on schedule.CourseId equals course.CourseId
                             join worker in _context.Workers on schedule.WorkerId equals worker.WorkerId
                             orderby schedule.CourseId descending
                             where schedule.ClassId == student.ClassId && schedule.Semester == Semester
                             select new
                             {
                                 SchoolSemester = schedule.SchoolSemester,
                                 CourseId = course.CourseId,
                                 CourseName = course.CourseName,
                                 CollegeId = schedule.CollegeId,
                                 WorkerId = worker.WorkerId,
                                 WorkerName = worker.WorkerName,
                                 ClassId = schedule.ClassId,
                                 ScheduleWeekly = schedule.ScheduleWeekly,
                                 ScheduleWeek = schedule.ScheduleWeek,
                                 ScheduleWhat = schedule.ScheduleWhat,
                                 SchedulePlace = schedule.SchedulePlace,
                                 Semester = schedule.Semester
                             }).ToList();
                List<Object> data = new List<Object>();
                for (int i = 0; i < scores.Count() -1 ; i++)
                {
                    if (scores.ElementAt(i).CourseId == scores.ElementAt(i + 1).CourseId) {
                        continue;
                    }
                    data.Add(scores.ElementAt(i));
                }
                AppLog.WriteInfo($"课表信息查询---学生{student.StuName}查询课表信息", true);
                return new ResultUtils() { code = 200, message = data };
            }
            else
            {
                AppLog.WriteError($"查询学生教评信息---教师{user.Username}登录", true);
                return new ResultUtils() { code = 500, message = $"查询学生教评信息---请使用学生账户登录" };
            }
        }

    }
}
